package com.engine.kq.cmd.balanceofleave;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.constant.*;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.LogUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import org.apache.commons.lang.StringUtils;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.systeminfo.SystemEnv;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 假期余额--批处理
 */
public class BatchProcessingCmd extends AbstractCommonCommand<Map<String, Object>> {

    BaseBean baseBean = new BaseBean();

    public BatchProcessingCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            BaseBean bb = new BaseBean();
            bb.writeLog("BatchProcessingCmd to do");

            boolean canEdit = HrmUserVarify.checkUserRight("KQLeaveRulesEdit:Edit", user);//是否具有新建权限
            if (!canEdit) {
                resultMap.put("status", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
                return resultMap;
            }
            /**前端返回的查询条件：*/
            /*假期类型的ID*/
            String ruleId = Util.null2String(params.get("ruleId"));

            // 外籍年假逻辑另外处理
            baseBean.writeLog("ruleId:" + ruleId);
            String wjnjid = baseBean.getPropValue("ss_prop_zm", "foreign_annual_leave_rule_id");
            if (StringUtils.equals(ruleId, wjnjid)) {
                baseBean.writeLog("skip foreign annual leave.");
                resultMap.put("sign", "1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(500961, user.getLanguage()));
                return resultMap;
            }
            baseBean.writeLog("start to handle data.");

            /*左侧点击的机构类型：0-总部、1-分部、2-部门*/
            int organizationType = Util.getIntValue((String) params.get("organizationType"), 0);

            /*左侧点击的机构的ID（例如：机构类型为分部时为分部ID）*/
            String organizationId = Util.null2String(params.get("organizationId"));

            /*搜索条件中的年份*/
            String searchYearSelect = Util.null2String(params.get("searchYearSelect"));//日期控件的选择值
            String searchYear = Util.null2String(params.get("searchYear"));//年份
            if (searchYearSelect.equals("5") || searchYearSelect.equals("8")) {
                searchYear = TimeUtil.getDateByOption(searchYearSelect, "0").substring(0, 4);
            }
            /*搜索条件中的人员姓名*/
            String hrmResourceId = Util.null2String(params.get("hrmResourceId"));
            //机构ID以及所有下级机构的ID
            String organizationIds = "";
            if (organizationType == 1) {
                SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
                organizationIds = subCompanyComInfo.getAllChildSubcompanyId(organizationId, organizationIds);
            } else if (organizationType == 2) {
                DepartmentComInfo departmentComInfo = new DepartmentComInfo();
                organizationIds = departmentComInfo.getAllChildDepartId(organizationId, organizationIds);
            }
            if (organizationIds.equals("")) {
                organizationIds = organizationId;
            } else {
                organizationIds = organizationId + organizationIds.trim();
            }
            if (!hrmResourceId.equals("")) {
                organizationType = 3;
                organizationIds = hrmResourceId;
            }

            if (ruleId.equals("")) {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(500956, user.getLanguage()));
                return resultMap;
            }
            if (searchYear.equals("")) {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(500957, user.getLanguage()));
                return resultMap;
            }

            if (organizationType != 0 && organizationIds.equals("")) {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(388858, user.getLanguage()));
                return resultMap;
            }

            /*假期二开---福利年假：法定年假未执行前不可执行福利年假start*/
            //获取法定年假和福利年假对应的假期类型
            //isLegalOrWelfare:是否为法定或福利年假，法定-1，福利-2，其他-0 or null
            Map<Integer, String> legalAndWelfareMap = new HashMap<>();
            String Legal = Util.null2String(bb.getPropValue("propExtends", "Legal"));
            String Welfare = Util.null2String(bb.getPropValue("propExtends", "Welfare"));
            legalAndWelfareMap.put( 1, Legal);
            legalAndWelfareMap.put( 2, Welfare);
//            Map<Integer, String> legalAndWelfareMap = new HashMap<>();
//            String acqLeaveTypeSql = "select ruleid,isLegalOrWelfare from kq_leaveRulesDetail where (isdelete is null or isdelete = 0) and isLegalOrWelfare in ( 1, 2 ) ";
//            RecordSet rs = new RecordSet();
//            rs.executeQuery(acqLeaveTypeSql);
//            while ( rs.next()) {
//                String ruleid = Util.null2String(rs.getString("ruleid"));
//                int isLegalOrWelfare = Util.getIntValue(Util.null2String(rs.getString("isLegalOrWelfare")));
//                if ( StringUtils.isNotBlank( ruleid) && isLegalOrWelfare > 0) {
//                    legalAndWelfareMap.put( isLegalOrWelfare, ruleid);
//                }
//            }

            bb.writeLog(" legalAndWelfareMap:" + legalAndWelfareMap);
            boolean flag = KQBalanceOfLeaveBiz.createData(ruleId, searchYear, organizationType, organizationIds, "" + user.getUID(), true, legalAndWelfareMap, false);
            /*假期二开---福利年假：法定年假未执行前不可执行福利年假end*/
            if (flag) {
                resultMap.put("sign", "1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(500961, user.getLanguage()));
            } else {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(500959, user.getLanguage()));
            }

            //获取当前日期，当前时间
            Calendar today = Calendar.getInstance();
            //当前日期
            String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" +
                    Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" +
                    Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            //当前时间
            String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
                    Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
                    Util.add0(today.get(Calendar.SECOND), 2);
            //记录日志
            BizLogContext bizLogContext = new BizLogContext();
            bizLogContext.setDateObject(new Date());
            bizLogContext.setDate(currentDate);
            bizLogContext.setTime(currentTime);
            bizLogContext.setUserid(user.getUID());
            bizLogContext.setUsertype(Util.getIntValue(user.getLogintype(),7));
            bizLogContext.setTargetId("");
            bizLogContext.setTargetName(""+ SystemEnv.getHtmlLabelName(15839,weaver.general.ThreadVarLanguage.getLang())+"");
            bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
            bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_BALANCEOFLEAVE);//所属大类型
            bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_BALANCEOFLEAVE);//当前小类型
            bizLogContext.setParams(params);//当前request请求参数
            bizLogContext.setClientIp((String) params.get(ParamConstant.PARAM_IP));
            bizLogContext.setDeviceType(BizLogDeviceType.PC);
            bizLogContext.setOperateType(BizLogOperateType.UPDATE);
            bizLogContext.setOperateAuditType(BizLogOperateAuditType.INFO);

            LogUtil.writeBizLog(bizLogContext);
        } catch (Exception e) {
            writeLog(e);
            resultMap.put("sign", "-1");
            resultMap.put("message",e.getMessage());
        }
        return resultMap;
    }
}
